<template>
  <div class="mod-prod">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('product.prodName') + ':'">
            <el-input
              v-model="searchForm.prodName"
              type="text"
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <el-form-item
            prop="status"
            :label="$t('product.status') + ':'"
          >
            <el-select
              v-model="searchForm.status"
              :placeholder="$t('product.status')"
              clearable
            >
              <el-option
                :label="$t('prodList.offShelf')"
                :value="0"
              />
              <el-option
                :label="$t('prodList.onShelf')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="isStockWarning"
            :label="$t('product.stockWarning') + ':'"
          >
            <el-select
              v-model="searchForm.isStockWarning"
              :placeholder="$t('product.stockWarning')"
              clearable
            >
              <el-option
                :label="$t('product.yes')"
                :value="1"
              />
              <el-option
                :label="$t('product.no')"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch(searchFormRef)"
            >
              {{ $t('station.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <div
          v-if="isAuth('distribution:distributionMsg:save')"
          class="default-btn primary-btn"
          @click.stop="onAddOrUpdate()"
        >
          {{ $t("seckill.newAdd") }}
        </div>
      </div>

      <!-- 表格 -->
      <div class="table-con score-prod-list-table">
        <el-table
          ref="scoreProdListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
        >
          <!-- 商品名称 -->
          <el-table-column
            fixed
            align="left"
            prop="prodName"
            width="320"
            :label="$t('product.prodName')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.prodName }}</span>
            </template>
          </el-table-column>
          <!-- 商品图片 -->
          <el-table-column
            prop="pic"
            :label="$t('product.pic')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <img-show :src="scope.row.pic" />
              </div>
            </template>
          </el-table-column>
          <!-- 商品原价 -->
          <el-table-column
            prop="oriPrice"
            :label="$t('product.marketPrice')"
          >
            <template #default="scope">
              {{ scope.row.oriPrice }}
            </template>
          </el-table-column>
          <!-- 商品现价 -->
          <el-table-column
            prop="price"
            :label="$t('product.sellingPrice')"
          >
            <template #default="scope">
              {{ scope.row.price }}
            </template>
          </el-table-column>
          <!-- 商品所需积分 -->
          <el-table-column
            width="110"
            prop="scorePrice"
            :label="$t('scoreProdList.needAccumulatePoints')"
          >
            <template #default="scope">
              {{ scope.row.scorePrice }}
            </template>
          </el-table-column>
          <!-- 商品库存 -->
          <el-table-column
            prop="totalStocks"
            :label="$t('product.availableInventory')"
          >
            <template #default="scope">
              {{ scope.row.totalStocks }}
            </template>
          </el-table-column>
          <!-- 状态 -->
          <el-table-column
            prop="status"
            :label="$t('product.status')"
          >
            <template #default="scope">
              <span v-if="scope.row.status === 0">{{ $t('prodList.offShelf') }}</span>
              <span v-if="scope.row.status === 1">{{ $t('prodList.onShelf') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="200"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('score:prod:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.prodId)"
                >
                  {{ $t("crud.updateBtn") }}
                </div>
                <div
                  v-if="scope.row.status === 0"
                  class="default-btn text-btn"
                  @click="onChangeProdStatus(scope.row.prodId, 1)"
                >
                  {{ $t("prodList.onShelf") }}
                </div>
                <div
                  v-if="scope.row.status === 1"
                  class="default-btn text-btn"
                  @click="onChangeProdStatus(scope.row.prodId, 0)"
                >
                  {{ $t("prodList.offShelf") }}
                </div>
                <div
                  v-if="scope.row.status > 1"
                  class="default-btn text-btn"
                  @click="onApplyAuditHandle(scope.row.prodId)"
                >
                  {{ $t("prodList.offShelfManage") }}
                </div>
                <div
                  v-if="isAuth('score:prod:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.prodId)"
                >
                  {{ $t("remindPop.delete") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 下线管理弹窗-->
    <ProdOfflineHandleEvent
      v-if="prodOfflineHandleEventVisible"
      ref="prodOfflineHandleEventRef"
      select-url="/prod/prod/getOfflineHandleEventByProdId"
      apply-url="/prod/prod/auditApply"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import ProdOfflineHandleEvent from '@/components/offline-event-handle/index.vue'
import { isAuth } from '@/utils/index'

const router = useRouter()
const route = useRoute()
const searchForm = ref({})
const prodOfflineHandleEventVisible = ref(false)
const prodNameRouter = ref('')
onMounted(() => {
  onGetDataList()
  if (route.query.prodName) {
    prodNameRouter.value = route.query.prodName
  }
})

// 获取数据列表
const dataListLoading = ref(false)
const dataForm = {
  prodName: ''
}
let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const onGetDataList = (pageParam, newData = false) => {
  dataListLoading.value = true

  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm.value))
  }
  http({
    url: http.adornUrl('/admin/scoreProduct/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          prodName: prodNameRouter.value || dataForm.prodName,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    for (const key in dataList.value) {
      if (Object.prototype.hasOwnProperty.call(dataList.value, key)) {
        const element = dataList.value[key]
        element.imgs = element.imgs.split(',')[0]
      }
    }
    dataForm.prodName = ''
    prodNameRouter.value = null
    page.value.total = data.total
    dataListLoading.value = false
  })
}
// 新增 / 修改
const onAddOrUpdate = (id) => {
  router.push({
    path: '/user/integrals-manage/score-prod-info/index',
    query: { prodId: id }
  })
}
// 删除
const onDelete = (id) => {
  ElMessageBox.confirm($t('scoreProdList.isDelete'), $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/admin/scoreProduct/${id}`),
        method: 'delete',
        data: http.adornData({})
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            onGetDataList(page.value)
          }
        })
      })
    })
    .catch(() => { })
}
const onChangeProdStatus = (id, status) => {
  ElMessageBox.confirm($t('remindPop.makeSure') + ' ' + `[${status ? $t('prodList.onShelf') : $t('prodList.offShelf')}]` + ' ' + $t('remindPop.operation') + '?', $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl('/admin/scoreProduct/prodStatus'),
        method: 'put',
        data: http.adornData({
          status,
          prodId: id
        })
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            onGetDataList(page.value)
          }
        })
      })
    })
}
// 条件查询
const onSearch = (newData = false) => {
  page.value.currentPage = 1
  onGetDataList(page.value, newData)
}

// 申请审核
const prodOfflineHandleEventRef = ref(null)
const onApplyAuditHandle = (id) => {
  prodOfflineHandleEventVisible.value = true
  nextTick(() => {
    prodOfflineHandleEventRef.value?.init(id)
  })
}
// 回调刷新
const refreshChange = () => {
  page.value.currentPage = 1
  onGetDataList()
}

/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const searchFormRef = ref(null)
const onResetSearch = (formName) => {
  formName.resetFields()
  searchForm.value = {}
}

const onPageSizeChange = (val) => {
  page.value.pageSize = val
  onGetDataList(page.value)
}
const onPageChange = (val) => {
  page.value.currentPage = val
  onGetDataList(page.value)
}

</script>
